package com.meals.system.service.impl;

import com.meals.system.api.seller.param.SystemSellerUpdateParam;
import com.meals.system.common.Constants;
import com.meals.system.common.ServiceResultEnum;
import com.meals.system.common.SystemException;
import com.meals.system.dao.SystemSellerMapper;
import com.meals.system.dao.SystemSellerTokenMapper;
import com.meals.system.entity.SystemSeller;
import com.meals.system.entity.SystemSellerToken;
import com.meals.system.service.WhitesMealSellerService;
import com.meals.system.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Description:
 * Parm:
 * return:
 * Author: Chen
 * Date: 2021/12/11
 */
@Service
public class WhitesMealSellerServiceImpl implements WhitesMealSellerService {

    @Autowired
    private SystemSellerMapper systemSellerMapper;

    @Autowired
    private SystemSellerTokenMapper systemSellerTokenMapper;


    @Override
    public String register(String loginName, String password) {
       if (systemSellerMapper.selectByLoginName(loginName) != null){
           return ServiceResultEnum.SAME_LOGIN_NAME_EXIST.getResult();
       }
        SystemSeller registerSeller = new SystemSeller();
        registerSeller.setLoginName(loginName);
        registerSeller.setNickName(loginName);
        registerSeller.setIntroduceSign(Constants.USER_INTRO);
        String passwordMd5 = MD5Util.MD5Encode(password,"UTF-8");
        registerSeller.setPasswordMd5(passwordMd5);
        if (systemSellerMapper.insertSelective(registerSeller) > 0){
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return ServiceResultEnum.DB_ERROR.getResult();
    }

    @Override
    public String login(String loginName, String passwordMD5) {
        SystemSeller systemSeller = systemSellerMapper.selectByLoginNameAndPassword(loginName, passwordMD5);
        if (systemSeller != null){
            if (systemSeller.getLockedFlag() == 1){
                return ServiceResultEnum.LOGIN_SELLER_LOCKED_ERROR.getResult();
            }
            // 登录后即执行token的操作
            String token = getNewToken(System.currentTimeMillis() + "",systemSeller.getSellerId());
            SystemSellerToken systemSellerToken = systemSellerTokenMapper.selectByPrimaryKey(systemSeller.getSellerId());
            // 当前时间
            Date now = new Date();
            // 过期时间
            Date expireTime = new Date(now.getTime() + 2 * 24 * 3600 * 1000);// 过期时间 48小时
            if (systemSellerToken == null){
                systemSellerToken = new SystemSellerToken();
                systemSellerToken.setSellerId(systemSeller.getSellerId());
                systemSellerToken.setToken(token);
                systemSellerToken.setUpdateTime(now);
                systemSellerToken.setExpireTime(expireTime);
                // 新增一条token数据
                if (systemSellerTokenMapper.insertSelective(systemSellerToken) > 0){
                    return token;
                }
            }
        }
        return ServiceResultEnum.LOGIN_ERROR.getResult();
    }

    @Override
    public Boolean updateSellerInfo(SystemSellerUpdateParam systemSeller, Long sellerId) {
        // 找到id对应的seller
        SystemSeller seller = systemSellerMapper.selectByPrimaryKey(sellerId);
        if (seller == null){
            SystemException.fail(ServiceResultEnum.DATA_NOT_EXIST.getResult());
        }
        seller.setNickName(systemSeller.getNickName());
        seller.setPasswordMd5(systemSeller.getPasswordMd5());
        // 若密码为空字符，则表明用户不打算修改密码，使用原密码保存
        if (!MD5Util.MD5Encode("", "UTF-8").equals(systemSeller.getPasswordMd5())){
            seller.setPasswordMd5(systemSeller.getPasswordMd5());
        }
        seller.setIntroduceSign(systemSeller.getIntroduceSign());
        if (systemSellerMapper.updateByPrimaryKeySelective(seller) > 0){
            return true;
        }
        return false;
    }

    @Override
    public Boolean logout(Long sellerId) {
        return systemSellerTokenMapper.deleteByPrimaryKey(sellerId) > 0;
    }

    @Override
    public PageResult getWhitesMealSellersPage(PageQueryUtil pageUtil){
        List<SystemSeller> systemSellers = systemSellerMapper.findSystemSellerList(pageUtil);
        int total = systemSellerMapper.getTotalSystemSeller(pageUtil);
        PageResult pageResult = new PageResult(systemSellers, total, pageUtil.getLimit(), pageUtil.getPage());
        return pageResult;
    }

    @Override
    public Boolean lockSellers(Long[] ids, int lockStatus){
        if (ids.length < 1){
            return false;
        }
        return systemSellerMapper.lockSellerBatch(ids, lockStatus) > 0;
    }


    /**
     * 获取token值
     *
     * @param timeStr
     * @param userId
     * @return
     */
    private String getNewToken(String timeStr, Long userId){
        String src = timeStr + userId + NumberUtil.genRandomNum(4);
        return SystemUtil.genToken(src);
    }


}
